package com.puffer.core.controller;

import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.puffer.core.domain.Navigation;
import com.puffer.core.service.MenuService;
import com.puffer.core.service.MenuServiceImpl;
import com.puffer.domain.SysUser;
import com.puffer.service.UserService;
import com.puffer.service.impl.UserServiceImpl;

@Controller
@RequestMapping(value = "puffer")
public class LoginController extends baseController  {

	final static Logger logger = LoggerFactory.getLogger("com.puffer.core.controller.LoginController.class");
	
	/**
	 * 用户登录
	 * 
	 * @return 登陆成功后的页面
	 */
	@RequestMapping("login")
	@ResponseBody
	public String login(SysUser user) {

		// 获取前台请求的用户名和密码
		String userId = request.getParameter("loginName");
		String pass = (String) request.getParameter("loginPwd");

		SysUser sysUser = null;

		// 获取session中的user信息
		sysUser = (SysUser) session.getAttribute("user");

		if (sysUser == null) {
			// 与数据库中的用户进行匹配
			UserService userService = new UserServiceImpl();
			sysUser = userService.findLoginUser(userId, pass);
			
			//将sysUser添加到session中
			session.setAttribute("user", sysUser);
		}
		
		// 验证失败，返回重新登录
		if (sysUser == null) {
			logger.info("login failed {},{},用户名密码不正确", userId, pass);
			
			session.setAttribute("status", "用户名密码错误！");
			
			return "failed";
//			return InternalResourceViewResolver.REDIRECT_URL_PREFIX + "/login.jsp";
		}
		logger.info("login success: {},欢迎使用系统！", userId, pass);
		
		
//		return "FrameAll";
		return "success";
	}

	@RequestMapping("logout")
	@ResponseBody
	public String logout() {
		logger.debug("logout");
		// 清空用户数据，跳转到login页面
		request.getSession().removeAttribute("status");
		session.removeAttribute("user");
		return "success";
	}

	@RequestMapping("initNavTree")
	@ResponseBody
	public List<Navigation> initTree() {
		logger.debug("{} initNavTree", "33");
		MenuService menuService = new MenuServiceImpl();
		return menuService.getPlatformNavigation();
	}
	
	@RequestMapping("FrameAll")
	public String redrict(){
		return "FrameAll";
	}
}
